package payrechargelogic

import (
	"context"
	model "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/recharge"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/utils"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"
	"math"
	"time"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RechargeListPageLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRechargeListPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeListPageLogic {
	return &RechargeListPageLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 充值记录查询
func (l *RechargeListPageLogic) RechargeListPage(in *rpc.RechargeListRequest) (*rpc.RechargeListResponse, error) {
	var commonResp rpc.CommonResp
	// parameter check

	// database operation
	orderList, total, err := model.NewRechargeOrderModel(l.ctx, l.svcCtx.Db).GetRechargeOrderList(in)
	if err != nil {
		commonResp.Code = xerrors.DBError
		commonResp.Message = "Database operation error"
		return &rpc.RechargeListResponse{CommonResp: &commonResp}, err
	}

	// 转换查询结果
	var records []*rpc.RechargeRecord
	for _, r := range orderList {
		records = append(records, &rpc.RechargeRecord{
			Id:        int64(r.ID),
			UserId:    r.UserID,
			OrderNo:   r.OrderNo,
			ChannelId: int32(r.ChannelID),
			Type:      int32(r.Type),
			Amount:    utils.Float64ToString(r.Amount),
			Status:    r.Status,
			CreatedAt: time.Unix(r.CreatedAt, 0).Format(time.RFC3339),
			UpdatedAt: time.Unix(r.UpdatedAt, 0).Format(time.RFC3339),
		})
	}

	// Calculate total pages
	totalPages := int64(math.Ceil(float64(total) / float64(in.PageSize)))
	pagination := rpc.Pagination{
		PageSize:  in.PageSize,
		Page:      in.Page,
		Total:     total,
		TotalPage: totalPages,
	}
	return &rpc.RechargeListResponse{
		Records:    records,
		Pagination: &pagination,
		CommonResp: &commonResp,
	}, nil
}
